from django.shortcuts import render
from django.http import HttpResponse, JsonResponse
from django.views import View
from django.db.models import Q
from django.core.paginator import Paginator

from .models import CourseOrg, CityDictModel, TeacherModel
from .forms import UserAskForm


class OrgListView(View):
    """课程机构首页"""
    def get(self, request):
        # 课程机构
        all_orgs = CourseOrg.objects.all()
        hot_orgs = all_orgs.order_by('-click_nums')[:5]
        # 城市
        all_citys = CityDictModel.objects.all()

        # 机构搜索
        search_keywords = request.GET.get('keywords', '')
        if search_keywords:
            all_orgs = CourseOrg.objects.filter(Q(name__icontains=search_keywords) | Q(desc__icontains=search_keywords))

        # 取出筛选城市
        city_id = request.GET.get('city', '')
        if city_id:
            all_orgs = all_orgs.filter(city_id=int(city_id))

        # 类别筛选
        catgory = request.GET.get('ct', '')
        if catgory:
            all_orgs = all_orgs.filter(catgory=catgory)

        # 排序方式
        sort = request.GET.get('sort', '')
        if sort:
            if sort == 'students':
                all_orgs = all_orgs.order_by('-students')
            elif sort == 'courses':
                all_orgs = all_orgs.order_by('-course_nums')

        # 统计有多少家机构
        org_count = all_orgs.count()

        # 分页
        paginator = Paginator(all_orgs, 2)
        page = request.GET.get('page')
        all_orgs = paginator.get_page(page)
        data = {
            'all_orgs': all_orgs,
            'all_citys': all_citys,
            'org_count': org_count,
            'city_id': city_id,
            'catgory': catgory,
            'hot_orgs': hot_orgs,
            'sort': sort,
        }
        return render(request, 'org-list.html', data)


class AddUserAskView(View):
    """添加我要学习表单信息"""
    def post(self, request):
        userask_form = UserAskForm(request.POST)
        if userask_form.is_valid():
            # form表单验证通过后直接保存到数据库
            userask_form.save(commit=True)
            return JsonResponse({"status": "success"})
        else:
            return JsonResponse({"status": "fail", "msg": "添加出错"})


class TeacherListView(View):
    """"""
    def get(self, request):
        pass